//
//  UIWindow+ZBDebugRound.m
//  SoamHNMengDong
//
//  Created by BO ZHOU on 2021/5/20.
//  Copyright © 2021 Goldwind. All rights reserved.
//

#import "UIWindow+ZBDebugRound.h"
#import <objc/runtime.h>
#import "ZBDebugView.h"

@implementation UIWindow (ZBDebugRound)


+(void)load {

    
#if DEBUG

    //方法交换只用执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        [self exchangeSystemSelector:@selector(setRootViewController:) swizzledSelector:@selector(exchange_setRootViewController:)];

    });
    
#endif
}

/**
 * 交换两个方法 (同一个类交换)
 */
+(void)exchangeSystemSelector:(SEL)systemSelector swizzledSelector:(SEL)swizzledSelector {
    // 两个方法的Method
    Method originalMethod = class_getInstanceMethod(self, systemSelector);
    Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
    //  动态添加方法
    if (class_addMethod(self, systemSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))) {
        // 添加成功的话将被交换方法的实现替换到这个并不存在的实现
        class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    }else {
        //添加不成功，交换两个方法的实现
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

-(void)exchange_setRootViewController:(UIViewController*)controller {
    
    [self exchange_setRootViewController:controller];
    
    dispatch_async(dispatch_get_main_queue(), ^{

        if (ZBDebugView.shared.isOpen) {
            [ZBDebugView show];
        }
    });
}


@end
